package util

import "sync"

// CacheMap 类型
type CacheMap[K comparable, V any] struct {
	locks sync.RWMutex
	maps  map[K]V
}

// NewCacheMap 初始化
func NewCacheMap[K comparable, V any]() *CacheMap[K, V] {
	cm := &CacheMap[K, V]{
		maps: make(map[K]V),
	}
	return cm
}

// Set 设置键值
func (cm *CacheMap[K, V]) Set(key K, value V) {
	cm.locks.Lock()
	defer cm.locks.Unlock()
	cm.maps[key] = value
}

// Get 根据键获取值
func (cm *CacheMap[K, V]) Get(key K) (V, bool) {
	cm.locks.Lock()
	defer cm.locks.Unlock()
	value, ok := cm.maps[key]
	return value, ok
}

// Delete 删除键
func (cm *CacheMap[K, V]) Delete(key K) {
	cm.locks.Lock()
	defer cm.locks.Unlock()
	delete(cm.maps, key)
}

// Keys 获取Map中所有的键
func (cm *CacheMap[K, V]) Keys() []K {
	cm.locks.Lock()
	defer cm.locks.Unlock()
	keys := make([]K, 0, len(cm.maps))
	for key := range cm.maps {
		keys = append(keys, key)
	}
	return keys
}

// Values 获取Map中所有的值
func (cm *CacheMap[K, V]) Values() []V {
	cm.locks.Lock()
	defer cm.locks.Unlock()
	values := make([]V, 0, len(cm.maps))
	for _, value := range cm.maps {
		values = append(values, value)
	}
	return values
}

// Size 返回集合的大小（元素个数）
func (cm *CacheMap[K, V]) Size() int {
	cm.locks.Lock()
	defer cm.locks.Unlock()
	return len(cm.maps) // 返回 map 的长度
}

// Clear 清空集合
func (cm *CacheMap[K, V]) Clear() {
	cm.locks.Lock()
	defer cm.locks.Unlock()
	cm.maps = make(map[K]V) // 重新初始化 map，从而清空集合
}
